﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraBars;
using System.IO;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using Data;

namespace GlobalCode
{
    public partial class GlobalCode : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public GlobalCode()
        {
            InitializeComponent();
            this.treeList1.DataSource = codelist;
            LoadToTree();
        }

        private List<codelist> codelist = new List<codelist>();

        private TreeListNode tn = null;

        /// <summary>
        /// 加载目录
        /// </summary>
        private void LoadToTree()
        {
            string thisExeDirectory = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string thisDirectory = thisExeDirectory + GlobalDirectory.SaveDirectory + "\\JSONCodeDataList";
            if (!Directory.Exists(thisDirectory))
            {
                Directory.CreateDirectory(thisDirectory);
            }
            DirectoryInfo TheFolder = new DirectoryInfo(thisDirectory);
            foreach (FileInfo NextFile in TheFolder.GetFiles())
            {
                AppendNode(NextFile.Name.TrimEnd(NextFile.Extension.ToCharArray()));
            }

        }

        /// <summary>
        /// 目录树右键 - 显示菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList_heads_MouseClick(object sender, MouseEventArgs e)
        {
            tn = getFocusNode(sender, e.Location);
            if (e.Button == MouseButtons.Right)
            {
                if (tn == null)
                {
                    popupMenu1.ItemLinks[0].Visible = true;
                    popupMenu1.ItemLinks[1].Visible = true;
                    popupMenu1.ItemLinks[2].Visible = true;
                }
                else {
                    popupMenu1.ItemLinks[0].Visible = false;
                    popupMenu1.ItemLinks[1].Visible = true;
                    popupMenu1.ItemLinks[2].Visible = true;
                }
                this.treeList1.SetFocusedNode(tn);
                popupMenu1.ShowPopup(MousePosition);
            }
        }

        /// <summary>
        /// 目录树左键双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList_heads_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            tn = getFocusNode(sender, e.Location);
            if (e.Button == MouseButtons.Left)
            {
                this.treeList1.SetFocusedNode(tn);
                opennode();
            }
        }

        /// <summary>
        /// 菜单添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
        {
            AppendNode();
        }

        /// <summary>
        /// 目录树节点不能编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList_heads_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            opennode();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {

            if (tn != null)
            {
                int opendnumber = (int)tn.GetValue("opendnumber");
                if (opendnumber == 0)
                {
                    string thisExeFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    string thisFile = thisExeFile + GlobalDirectory.SaveDirectory + "\\JSONCodeDataList\\" + tn.GetValue("Key") + ".json";
                    if (File.Exists(thisFile))
                    {
                        File.Delete(thisFile);
                    }
                    else
                    {
                        XtraMessageBox.Show("此节点对应的数据不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    }
                    this.treeList1.DeleteNode(tn);
                }
                else
                {
                    XtraMessageBox.Show("此节点已打开请先关闭！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                }

            }
        }

        /// <summary>
        /// 获取当前节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static TreeListNode getFocusNode(Object sender, Point p)
        {
            TreeList currentTreeList = sender as TreeList;
            TreeListHitInfo hitinfo = currentTreeList.CalcHitInfo(p);
            if (hitinfo.Node != null)
            {
                return hitinfo.Node;
            }
            return null;
        }

        /// <summary>
        /// 添加节点
        /// </summary>
        private void AppendNode(string name = "新建标签")
        {
            List<codelist> dd = (List<codelist>)this.treeList1.DataSource;
            if (dd.Count > 0)
            {
                this.treeList1.AppendNode(new object[] { name, 0, "", System.Guid.NewGuid().ToString(), "" }, -1);
            }
            else
            {
                dd.Add(new codelist()
                {
                    Key = name,
                    Data = "",
                    opendnumber = 0,
                    ID = System.Guid.NewGuid().ToString(),
                    ParentID = ""
                });
                this.treeList1.RefreshDataSource();
            }
            this.treeList1.ExpandAll();
        }

        /// <summary>
        /// 打开节点
        /// </summary>
        private void opennode()
        {

            if (tn != null)
            {
                string thisExeFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                string thisFile = thisExeFile + GlobalDirectory.SaveDirectory + "\\JSONCodeDataList\\" + tn.GetValue("Key") + ".json";
                codelist NodeDatalist = null;
                if (File.Exists(thisFile))
                {
                    using (StreamReader file = File.OpenText(thisFile))
                    {
                        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                        NodeDatalist = (codelist)serializer.Deserialize(file, typeof(codelist));
                        NodeDatalist.opendnumber = 1;
                    }
                }else{
                    NodeDatalist = new codelist
                    {
                        Key = tn.GetValue("Key").ToString(),
                        Data = "",
                        opendnumber = 1,
                        ID = System.Guid.NewGuid().ToString(),
                        ParentID = ""
                    };
                }
                tn.SetValue("opendnumber", 1);

                

                XtraTabPage page = new XtraTabPage();

                GlobalCodeEdit gc = new GlobalCodeEdit(tn, NodeDatalist, page);
                gc.Dock = DockStyle.Fill;

                page.Text = NodeDatalist.Key;
                page.Controls.Add(gc);


                this.xtraTabControl1.TabPages.Add(page);
                this.xtraTabControl1.SelectedTabPage = page;
            }
        }

        /// <summary>
        /// 标签关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void xtraTabControl1_CloseButtonClick(object sender, EventArgs e)
        {
            XtraTabControl s = (XtraTabControl)sender;
            XtraTabPage t = s.SelectedTabPage;
            int opendnumber = (int)tn.GetValue("opendnumber");
            tn.SetValue("opendnumber", opendnumber - 1);
            t.Dispose();
        }

    }

    public class codelist : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _Key;
        public string Key
        {
            get { return _Key; }
            set
            {
                if (value.Length < 16)
                {
                    _Key = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Key"));
                    }
                }
            }
        }

        private int _opendnumber = 0;
        public int opendnumber { get { return _opendnumber; } set { _opendnumber = value; } }

        public string Data { get; set; }


        #region 节点目录结构一定要放置到最后

        /// <summary>
        /// 当前节点ID
        /// </summary>
        public string ID { get; set; }

        /// <summary>
        /// 父节点ID
        /// </summary>
        public string ParentID { get; set; }

        #endregion
    }
}